export default class EventSubscribe {
  constructor(args) {
    this.Channels = {}; // key-通道名   value-通道处理函数数组
  }

  //订阅
  subScrible(channcel, callback) {
    if (!this.Channels[channcel]) {
      this.Channels[channcel] = [];
    }
    this.Channels[channcel].push(callback);
    return this;
  }

  //订阅 （只执行一次）
  subScribleOnce(channcel, callback) {
    const onceCb = (...args) => {
      callback.apply(this, args);
      this.unSubscrible(channcel, onceCb);
    };
    this.subScrible(channcel, onceCb);
  }

  //取消订阅
  unSubscrible(channcel, callback) {
    if (!this.Channels[channcel]) {
      return;
    }
    if (!callback) {
      //不指定  取消的处理函数， 默认取消通道上得所有
      this.Channels[channcel] = [];
    }

    this.Channels[channcel] = this.Channels[channcel].filter((cb) => {
      return cb != callback;
    });
  }

  // 发布
  public(channcel, ...args) {
    let cbBackList = []; //通道 channcel 中 订阅的函数返回结果的集合
    this.Channels[channcel]?.forEach((cb) => {
      //console.log("this", this);
      const cbBack = cb.apply(this, args);
      if (cbBack) {
        //如果函数有返回
        cbBackList.push(cbBack);
      }
    });
    return cbBackList;
  }
}
